package com.mage.dao.impl;

import com.mage.bean.PageBean;
import com.mage.bean.Record;
import com.mage.bean.User;
import com.mage.dao.RecordDao;
import com.mage.dao.UserDao;
import com.mage.tool.JDBCUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class RecordDaoImpl implements RecordDao {
    @Override
    public PageBean findRecordByPages(int currentPage) throws SQLException {
            //封装分页的该页数据
            PageBean<Record> pageBean = new PageBean<Record>();

            int pageSize = RecordDao.PAGE_SIZE ;
            currentPage=currentPage<1?1:currentPage;
            pageBean.setCurrentPage(currentPage); //设置当前页
            pageBean.setPageSize(pageSize); //设置每页显示多少记录

            RecordDao dao = new RecordDaoImpl() ;
            List<Record> list =dao.findRecordByPage(currentPage);
            pageBean.setList(list); //设置这一页的学生数据

            //总的记录数， 总的页数。
            int count = dao.findCount();
            pageBean.setTotalSize(count); //设置总的记录数
            //200 ， 10 ==20   201 ， 10 = 21   201 % 10 == 0 ?201 / 10 :201 % 10 + 1
            pageBean.setTotalPage(count % pageSize==0 ? count / pageSize : (count / pageSize) + 1); //总页数
            return pageBean;
    }

    @Override
    public List<Record> findRecordByPage(int currentPage) throws SQLException {
        QueryRunner runner = new QueryRunner(JDBCUtil.getDataSource());
        return runner.query("select * from record limit ? offset ?", new BeanListHandler<Record>(Record.class), PAGE_SIZE , (currentPage-1)*PAGE_SIZE);
    }


    public int findCount() throws SQLException {
        QueryRunner runner = new QueryRunner(JDBCUtil.getDataSource());
        Long  result = (Long) runner.query("SELECT COUNT(*) FROM record " , new ScalarHandler() );
        return result.intValue();
    }

    @Override
    public void insert(Record record) throws SQLException {
        QueryRunner runner = new QueryRunner(JDBCUtil.getDataSource());
        runner.update("insert into record (createtime,userid,username,address,content,amount) values(?,?,?,?,?,?)",
                record.getCreatetime(),
                record.getUserid(),
                record.getUsername(),
                record.getAddress(),
                record.getContent(),
                record.getAmount()
        );
    }
}
